<template>
  <div>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <el-form inline>
        <el-form-item>
          <el-input
            placeholder="请输入用户名"
            v-model="paramsState.username"
            size="small"
          ></el-input>
        </el-form-item>
        <el-button type="primary" size="default" @click="search">查询</el-button
        ><el-button size="default" @click="resetSearch">清空</el-button>
      </el-form>

      <div style="margin: 20px 0">
        <el-button type="primary" @click="showAddUser">添加</el-button>
        <el-button type="danger" @click="revomveSelectedUsers"
          >批量删除</el-button
        >
      </div>

      <el-table
        border
        stripe
        :data="userList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" width="80" label="序号" />
        <el-table-column prop="username" label="用户名" width="150" />
        <el-table-column prop="nickName" label="用户昵称" />
        <el-table-column prop="roleName" label="角色列表" width="200" />

        <el-table-column prop="gmtCreate" label="创建时间" width="180" />
        <el-table-column prop="gmtModified" label="更新时间" width="180" />

        <el-table-column label="操作" width="200" fixed="right">
          <template v-slot="{ row }">
            <el-button
              type="info"
              size="small"
              icon="el-icon-user-solid"
              title="分配角色"
              @click="showAssignRole(row)"
            ></el-button>
            <el-button
              type="primary"
              size="small"
              icon="el-icon-edit"
              title="修改用户"
              @click="showUpdateUser(row)"
            ></el-button>

            <el-button
              style="margin-left:10px"
              type="danger"
              size="small"
              icon="el-icon-delete"
              title="删除用户"
              @click="removeUser(row.id)"
            />
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>

    <el-dialog
      :title="userList.id ? '修改用户' : '添加用户'"
      :visible.sync="dialogUserVisible"
      width="50%"
    >
      <el-form
        ref="userFormRef"
        :model="user"
        :rules="userRules"
        label-width="120px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="user.username" />
        </el-form-item>
        <el-form-item label="用户昵称">
          <el-input v-model="user.nickName" />
        </el-form-item>

        <el-form-item v-if="!user.id" label="用户密码" prop="password">
          <el-input v-model="user.password" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogUserVisible = false">取消</el-button>
        <el-button type="primary" @click="addOrUpdate">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog
      title="设置角色"
      :visible.sync="roleState.dialogRoleVisible"
      :before-close="resetRoleData"
    >
      <el-form label-width="80px">
        <el-form-item label="用户名">
          <el-input disabled :value="user.username"></el-input>
        </el-form-item>

        <el-form-item label="角色列表">
          <el-checkbox
            :indeterminate="roleState.isIndeterminate"
            v-model="roleState.checkAll"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group
            v-model="roleState.userRoleIds"
            @change="handleCheckedChange"
          >
            <el-checkbox
              v-for="role in roleState.allRoles"
              :key="role.id"
              :label="role.id"
              >{{ role.roleName }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button
          :loading="roleState.roleLoading"
          type="primary"
          @click="assignRoleSave"
          >保存</el-button
        >
        <el-button @click="resetRoleData">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  reqUserList,
  reqAddUser,
  reqUpdateUser,
  reqRole,
  reqAssign,
  reqDeleteUser,
  reqDeleteSelectedUser
} from "@/api/acl/user";
export default {
  name: "User",
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value.length > 10) {
        callback(new Error("用户名的长度不能大于10"));
      } else {
        callback();
      }
    };
    const validateNickName = (rule, value, callback) => {
      if (value.length > 10) {
        callback(new Error("用户昵称的长度不能大于10"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value.length > 10) {
        callback(new Error("密码的长度不能大于10"));
      } else {
        callback();
      }
    };

    return {
      currentPage: 1,
      pageSize: 5,
      pageSizes: [5, 10, 15],
      total: 0,
      userList: [],
      dialogUserVisible: false,
      user: {
        id: "",
        username: "",
        nickName: "",
        password: ""
      },
      userRules: {
        username: [
          {
            required: true,
            validator: validateUsername,
            trigger: ["blur", "change"]
          }
        ],
        nickName: [
          {
            required: false,
            validator: validateNickName,
            trigger: ["blur", "change"]
          }
        ],
        password: [
          {
            required: true,
            validator: validatePassword,
            trigger: ["blur", "change"]
          }
        ]
      },
      roleState: {
        dialogRoleVisible: false,
        roleLoading: false,
        checkAll: false,
        isIndeterminate: false,
        userRoleIds: [],
        allRoles: []
      },
      tableState: {
        total: 0,
        users: [],
        selectedIds: []
      },
      paramsState: {
        username: "",
        searchUsername: "",
        page: 1, // 当前页码
        limit: 5 // 每页数量
      }
    };
  },
  methods: {
    // 每页条数和当前页的改变
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.pageSize = val;
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.currentPage = val;
    },
    // 初始化用户列表
    async getUserList() {
      try {
        let result = await reqUserList(this.currentPage, this.pageSize, {
          username: this.paramsState.searchUsername
        });
        this.userList = result.data.items;

        this.total = result.data.total;

        this.tableState.users = result.data.items;
        this.tableState.total = result.data.total;
        // this.tableState.selectedIds = [];
      } catch (error) {
        alert(error.message);
      }
    },
    // 点击添加按钮
    showAddUser() {
      this.dialogUserVisible = true;

      this.user = {
        id: "",
        username: "",
        nickName: "",
        password: ""
      };
    },
    // 新增或更新用户信息
    async addOrUpdate() {
      await this.$refs.userFormRef.validate();

      try {
        if (this.user.id) {
          await reqUpdateUser(this.user);
          this.$message({
            message: "修改品牌成功",
            type: "success"
          });
        } else {
          await reqAddUser(this.user);

          this.$message({
            message: "新增用户成功",
            type: "success"
          });
        }

        this.dialogUserVisible = false;

        this.getUserList();
      } catch (error) {
        return this.$message({
          message: error,
          type: "error"
        });
      }
    },
    // 更新用户信息
    showUpdateUser(row) {
      this.user = { ...row };
      this.dialogUserVisible = true;
    },
    //   显示指定角色的界面
    showAssignRole(row) {
      this.user = row;
      this.roleState.dialogRoleVisible = true;
      this.getRoles();
    },
    // 获取用户的角色列表
    async getRoles() {
      const result = await reqRole(this.user.id);
      //   console.log(result);
      const { allRolesList, assignRoles } = result.data;

      this.roleState.allRoles = allRolesList;
      this.roleState.userRoleIds = assignRoles.map(item => item.id);
      this.roleState.checkAll = allRolesList.length === assignRoles.length;
      this.roleState.isIndeterminate =
        assignRoles.length > 0 && assignRoles.length < allRolesList.length;
    },
    // 重置角色数据
    resetRoleData() {
      this.roleState = {
        dialogRoleVisible: false,
        allRoles: [],
        userRoleIds: [],
        isIndeterminate: false,
        checkAll: false
      };
    },
    //   全选勾选状态发生改变的监听
    handleCheckAllChange(value) {
      this.roleState.userRoleIds = value
        ? this.roleState.allRoles.map(item => item.id)
        : [];
      this.roleState.isIndeterminate = false;
    },
    //   角色列表选中项发生改变的监听
    handleCheckedChange() {
      const { userRoleIds, allRoles } = this.roleState;
      this.roleState.checkAll =
        userRoleIds.length === allRoles.length && allRoles.length > 0;
      this.roleState.isIndeterminate =
        userRoleIds.length > 0 && userRoleIds.length < allRoles.length;
    },
    //   请求给用户进行角色授权
    async assignRoleSave() {
      try {
        //   console.log(this.user);
        const userId = this.user.id;
        //   console.log(userId);
        const roleIds = this.roleState.userRoleIds.join(",");
        await reqAssign(userId, roleIds);

        this.$message({
          message: "分配角色成功",
          type: "success"
        });

        this.resetRoleData();
        this.getUserList();
      } catch (error) {
        return this.$message({
          message: error,
          type: "error"
        });
      }
    },
    // 删除用户
    async removeUser(id) {
      await reqDeleteUser(id);
      this.$message({
        message: "删除用户成功",
        type: "success"
      });

      this.getUserList();
    },
    // 列表选中状态发生改变的监听回调
    handleSelectionChange(selection) {
      this.tableState.selectedIds = selection.map(item => item.id);
    },
    //   删除所有选中的用户
    async revomveSelectedUsers() {
      try {
        await reqDeleteSelectedUser(this.tableState.selectedIds);
        this.$message({
          message: "删除用户成功",
          type: "success"
        });
        this.getUserList();
      } catch (error) {
        return this.$message({
          message: error.message,
          type: "error"
        });
      }
    },
    // 查询
    search() {
      this.paramsState.searchUsername = this.paramsState.username;
      this.getUserList(1);
    },
    // 清空查询
    resetSearch() {
      this.paramsState.searchUsername = "";
      this.paramsState.username = "";
      this.getUserList();
    }
  },
  mounted() {
    this.getUserList();
  },
  watch: {
    currentPage: {
      immediate: true,
      handler() {
        this.getUserList();
      }
    },
    pageSize: {
      immediate: true,
      handler() {
        this.getUserList();
      }
    }
  }
};
</script>

<style></style>
